﻿using System.Text.Json.Serialization;
using Core.Caching;
using Core.Helpers;
using Core.Identity.Common.Interfaces.Common.Interfaces;
using Core.Identity.Roles.Caching;
using Core.Interfaces.Users;
using Core.Models;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Core.Identity.Roles.Features.Commands.BatchDelete;

/// <summary>
/// 删除角色
/// </summary>
public class BatchDeleteRoleCommand : ICacheInvalidatorRequest<Result<bool>>
{
    /// <summary>
    /// 删除的ID集合
    /// </summary>
    public required List<Guid> RoleIds { get; set; }

    [JsonIgnore]
    public IEnumerable<string>? Tags => RolesCacheKey.Tags;
}

public class BatchDeleteRoleCommandHandler(IIdentityDbContext dbContext) : IRequestHandler<BatchDeleteRoleCommand, Result<bool>>
{

    public async Task<Result<bool>> Handle(BatchDeleteRoleCommand request, CancellationToken cancellationToken)
    {
        var roles = await dbContext.Roles.Where(x => request.RoleIds.Contains(x.Id)).ToListAsync(cancellationToken);
        ExceptionHelper.ThrowIfTrue(roles == null || !roles.Any(), "数据不存在");

        dbContext.Roles.RemoveRange(roles!);
        var result = await dbContext.SaveChangesAsync(cancellationToken) > 0;

        return await Result<bool>.SucceedAsync(result, result, ["删除失败"]);
    }
}
